

# 查找所有case,组成测试套件
import os
import re
import time
import unittest
import HTMLTestRunner
from common.log import logger
from common.dingTalk import DingTalk
path_dir=os.path.dirname(__file__)
case_path=path_dir+r"/testCase/"
report_path=path_dir+r"/testReport/"

def create_suite():
    suite=unittest.defaultTestLoader.discover(start_dir=case_path,pattern="*Test.py")
    logger.info(f"查找的测试套件为{suite}")
    return suite

def gen_report(suite,x):
    cur_time=time.strftime('%Y_%m_%d_%H_%M_%S',time.localtime())
    report=report_path+cur_time+x.replace(':','.')+'report.html'
    with open(report,"wb") as fp:
        runner=HTMLTestRunner.HTMLTestReportCN(stream=fp,title="appium自动化测试报告",tester="橙好")
        runner.run(suite)
    return report

# def auto_clear():
#     filelist=os.listdir(report_path)
#     filelist.sort(key=lambda x :os.path.getctime(report_path+x))
#     for i in filelist[:-3]:
#         os.remove(report_path+i)

# def send_Msg(report):
#     pattern='<strong>测试结果 : </strong>(.*?)</p>'
#     with open(report,"r",encoding="utf8") as fp:
#         text=fp.read()
#         res=re.findall(pattern,text)
#         logger.info(f"获取到的标题名为{res}")
#     os.chdir(report_path)
#     os.system('python -m http.server 8888')
#     text = res
#     link = 'http://192.168.3.206:8888/report1.html'
#     # 发送钉钉通知
#     from common.dingTalk import DingTalk
#     DingTalk().send_link(text,link)

def run(x,y):
    print("~~~~~~~~~~~~")
    from common.driver import Driver
    Driver.deviceName=x
    Driver.port=y

    suite = create_suite()
    report = gen_report(suite,x)
    print(report)

    # send_Msg(report)

if __name__ == '__main__':
    serverList = [('127.0.0.1:21503', 4723), ('127.0.0.1:21513', 4725)]
    from multiprocessing import Pool

    pool = Pool(len(serverList))
    re = []
    for i, j in serverList:
        res = pool.apply_async(run, (i, j))
        re.append(res)
    for i in re:
        i.get()
    print("finshed")
    # auto_clear()